package com.xiaojie.schedule;

import com.xiaojie.entity.User;
import com.xiaojie.lock.RedisDistributeLock;
import com.xiaojie.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;

/**
 * @ClassMyTask
 * @Description 模拟定时任务
 * @AuthorAdministrator
 * @Date {Date}{Time}
 * @Version 1.0
 **/
@Component
public class MyTask {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisDistributeLock  redisDistributeLock;
    private static final String REDISKEY = "xiaojie_redis_lock";
    private static final Integer NOLOCK_TIMEOUT=5;
    private static final Long TIME_OUT=5L;
    private static final String value= UUID.randomUUID().toString();
     int i;
    @Scheduled(cron = "* * * 5 * ? ")
    public void scheduledTask(){
        String lockValue = redisDistributeLock.getLock(REDISKEY, NOLOCK_TIMEOUT, TIME_OUT);
        if(StringUtils.isBlank(lockValue)){
            System.out.println("获取锁失败");
            return;
        }

        List<User> users = userMapper.selectAll();
        for (User user:users){
            user.setNum(user.getNum()+1);
            int updateNum = userMapper.updateNum(user.getNum(),user.getId());
            System.out.println(updateNum);
        }
        i++;
        System.out.println("执行了"+i+"次");
        //释放锁
        redisDistributeLock.unLock(REDISKEY,lockValue);
    }

}
